﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using coffeeshop.Models;

namespace coffeeshop.Forms
{
    public partial class frmOrderCurrentTable : Form
    {
        #region "Parameters"

        private System.Resources.ResourceManager mv_Resources = new System.Resources.ResourceManager("coffeeshop.Properties.Resources", System.Reflection.Assembly.GetExecutingAssembly());
        public int currentWorkTime { get; set; }
        public string CaLam { get; set; }        
        public OrderTable objOrderTable { get; set; }
        public Form MyParentForm { get; set; }
        #endregion

        #region "Funtions"

        public frmOrderCurrentTable(OrderTable v_objOrderTable, int v_currentWorkTime)
        {
            InitializeComponent();
            
            if (v_objOrderTable != null)
            {
                objOrderTable = v_objOrderTable;
                currentWorkTime = v_currentWorkTime;
                LoadOrderTableDescription();
                LoadWaiterList();
                if (objOrderTable != null)
                {
                    ResetDisplay();                    
                }
                else
                {
                    MessageBox.Show(mv_Resources.GetString("ERROR.DISPLAY"));
                }

            }            
        }

        private void LoadOrderTableDescription()
        {
            if (objOrderTable != null)
            {
                objOrderTable = OrderTable.GetTableOrderById(objOrderTable.TableOrderId);
            }
        }

        private void LoadWaiterList()
        {
            lblWaiter.Text = mv_Resources.GetString("FRMORDERDETAIL.WAITER");
            coffeeDataSet.UserDataTable waiterDataList = User.GetPhucVu();
            cboWaiter.DataSource = waiterDataList;
            cboWaiter.ValueMember = "UserId";
            cboWaiter.DisplayMember = "Name";
            cboWaiter.SelectedIndex = -1;
        }

        private void ResetDisplay()
        {
            try
            {
                this.Text = mv_Resources.GetString("FRMORDERDETAILNAME") + objOrderTable.TableOrderName;
                lblTableName.Text = mv_Resources.GetString("TABLENAME") + objOrderTable.TableOrderName;
                lblStatus.Text = Global.GetTableOrderStatus(objOrderTable.Status);

                dgvProductList.Columns.Add("ProductName", mv_Resources.GetString("FRMORDERCURRENTTABLE.PRODUCTNAME"));
                dgvProductList.Columns.Add("UnitName", mv_Resources.GetString("FRMORDERCURRENTTABLE.UNITNAME"));
                dgvProductList.Columns.Add("Quantity", mv_Resources.GetString("FRMORDERCURRENTTABLE.QUANTITY"));
                dgvProductList.Columns.Add("Price", mv_Resources.GetString("FRMORDERCURRENTTABLE.PRICE"));
                dgvProductList.Columns.Add("Value", mv_Resources.GetString("FRMORDERCURRENTTABLE.VALUE"));
                dgvProductList.Columns.Add("ProductId", mv_Resources.GetString("ProductId")); 
                dgvProductList.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
                dgvProductList.Columns[5].Visible = false;
                                
                txtDiscount.Text = "0";                
                lblEstimateSum.Text = mv_Resources.GetString("FRMORDERCURRENTTABLE.ESTSUM");
                lblDiscount.Text = mv_Resources.GetString("FRMORDERCURRENTTABLE.DISCOUNT");                
                lblStatusName.Text = mv_Resources.GetString("FRMORDERDETAIL.STATUS").ToUpper();
                lblSum.Text = mv_Resources.GetString("FRMORDERCURRENTTABLE.SUM");

                btnPrintBill.Text = mv_Resources.GetString("FRMORDERCURRENTTABLE.PRINTBILL");
                btnExitNone.Text = mv_Resources.GetString("FRMORDERCURRENTTABLE.EXITNONE");
                btnExitPrint.Text = mv_Resources.GetString("FRMORDERCURRENTTABLE.EXITPRINT");
                btnAddOrder.Text = mv_Resources.GetString("FRMORDERCURRENTTABLE.ADDORDER");
                btnMergeTable.Text = mv_Resources.GetString("FRMORDERCURRENTTABLE.MERGEORDER");
                btnCancelOrder.Text = mv_Resources.GetString("FRMORDERCURRENTTABLE.CANCELORDER");


                // Load current order.  
                if (objOrderTable.Status != Global.TableStatus.Available)
                {
                    LoadCurrentOrders();
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void LoadCurrentOrders()
        {            
            Double dblPrice = 0, dblValue = 0, dblSum = 0;
            OrderDetail objOrderDetail = new OrderDetail();
            coffeeDataSet.OrderDetailDataTable objOrderDetailData = new coffeeDataSet.OrderDetailDataTable();

            objOrderDetailData = objOrderDetail.getOrderDetail(objOrderTable.TableOrderId);
            if (objOrderDetailData.Any())
            {
                dgvProductList.Rows.Clear();
                dblSum = 0;
                foreach (coffeeDataSet.OrderDetailRow aRow in objOrderDetailData.Rows)
                {                    
                    DataGridViewRow newRow = new DataGridViewRow();
                    newRow.CreateCells(dgvProductList);
                    newRow.Cells[0].Value = aRow["ProductName"];
                    newRow.Cells[1].Value = aRow["UnitName"];
                    newRow.Cells[2].Value = aRow["Quantity"];
                    dblPrice = Convert.ToDouble(aRow["Price"]);
                    newRow.Cells[3].Value = dblPrice.ToString("#,##0");
                    dblValue = dblPrice * Convert.ToDouble(aRow["Quantity"]);
                    newRow.Cells[4].Value = dblValue.ToString("#,##0");
                    newRow.Cells[5].Value = aRow["ProductId"];
                    // If row exists in datagridview => add quantity Else add new row.
                    if (!UpdateCurrentRow(newRow))
                    {
                        dgvProductList.Rows.Add(newRow);
                    }
                    dblSum = dblSum + dblValue;
                    cboWaiter.SelectedValue = aRow["OrderedBy"];
                }
            }
            txtEstimateSum.Text = dblSum.ToString("#,##0");
            txtSum.Text = dblSum.ToString("#,##0");
        }

        private bool UpdateCurrentRow(DataGridViewRow addRow)
        {
            bool blnIsExist = false;
            double result = 0;
            foreach (DataGridViewRow currentRow in dgvProductList.Rows)
            {
                if (Convert.ToInt16(currentRow.Cells[5].Value) == Convert.ToInt16(addRow.Cells[5].Value))
                {
                    //Quantity
                    result = Convert.ToInt16(currentRow.Cells[2].Value) + Convert.ToInt16(addRow.Cells[2].Value);
                    currentRow.Cells[2].Value = result;
                    //Price * Quantity
                    result = Convert.ToDouble(currentRow.Cells[3].Value.ToString().Replace(",", "")) * result;
                    currentRow.Cells[4].Value = result.ToString("#,##0");
                    blnIsExist = true;
                    break;
                }
            }
            return blnIsExist;
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (txtDiscount.Focused)
                return base.ProcessCmdKey(ref msg, keyData);

            if (keyData == Keys.D0)
            {
                PrintBill();                
                return true;
            }
            if (keyData ==Keys.D1)
            {
                this.Close();
                return true;
            }
            if (keyData == Keys.D2)
            {
                PrintBill();
                this.Close();
                return true;
            }
            if (keyData == Keys.D3)
            {
                AddOrder();
                return true;
            }
            if (keyData == Keys.D4)
            {
                MergeOrder();
                return true;
            }
            if (keyData == Keys.D5)
            {
                CancelOrder();
                return true;
            }

            return base.ProcessCmdKey(ref msg, keyData);
        } 

        private void PrintBill()
        {
            MessageBox.Show("printing bill");
        }

        private void AddOrder()
        {
            frmListTables parentForm = (frmListTables)MyParentForm;
            CaLam = parentForm.CaLam;

            OrderTable cancelOrderTable = new OrderTable(objOrderTable.TableOrderId);
            frmOrderDetail frmNew = new frmOrderDetail(objOrderTable, currentWorkTime, Global.OrderType.OrderPlus);
            frmNew.MyParentForm = this;
            frmNew.StartPosition = FormStartPosition.CenterScreen;
            frmNew.ShowDialog();
            LoadCurrentOrders();
        }

        private void MergeOrder()
        {
            MessageBox.Show("merging tables");
        }

        private void CancelOrder()
        {
            frmListTables parentForm = (frmListTables)MyParentForm;
            CaLam = parentForm.CaLam;

            OrderTable cancelOrderTable = new OrderTable(objOrderTable.TableOrderId);
            frmOrderDetail frmNew = new frmOrderDetail(objOrderTable, currentWorkTime, Global.OrderType.OrderReturn);
            frmNew.MyParentForm = this;
            frmNew.StartPosition = FormStartPosition.CenterScreen;
            frmNew.ShowDialog();
            LoadCurrentOrders();
        }

        #endregion

        #region "Events"

        private void txtDiscount_Validating(object sender, CancelEventArgs e)
        {
            try
            {
                if (Convert.ToDouble(txtDiscount.Text.Trim()) < 0)
                {
                    MessageBox.Show(mv_Resources.GetString("FRMORDERCURRENTTABLE.CHECKDISCOUNT"),"ERROR",MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtDiscount.Focus();
                }
                else
                {
                    Double dblSum = Convert.ToDouble(txtEstimateSum.Text.Trim());
                    dblSum = Math.Round((dblSum * (100 - Convert.ToDouble(txtDiscount.Text.Trim())) / 100) / 100) * 100;
                    txtSum.Text = dblSum.ToString("#,##0");
                }                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void txtDiscount_Enter(object sender, EventArgs e)
        {
            txtDiscount.SelectAll();            
        }

        private void btnExitNone_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnPrintBill_Click(object sender, EventArgs e)
        {
            PrintBill();
        }

        private void btnExitPrint_Click(object sender, EventArgs e)
        {
            PrintBill();
            this.Close();
        }

        private void btnAddOrder_Click(object sender, EventArgs e)
        {
            AddOrder();
        }

        private void btnMergeTable_Click(object sender, EventArgs e)
        {
            MergeOrder();
        }

        private void btnCancelOrder_Click(object sender, EventArgs e)
        {
            CancelOrder();
        }
        #endregion          
    }
}
